package com.yyge.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @program: js-hd
 * @description: 字符串工具类
 * @author: gityyge
 * @create: 2024-01-29 15:20
 **/

public class StringUtil {
    private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMBERS = "0123456789";
    private static final String SPECIAL_CHARACTERS = "!@#$%^&*()_+-=[]{};:'\\|,.<>/?`&#126;";
    private static final String ALL = UPPERCASE + LOWERCASE + NUMBERS + SPECIAL_CHARACTERS;
    private static final String LOWERANDNUM = LOWERCASE + NUMBERS; //小写字母+数字  type=0


    public static String getRandomString(int length,int type) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            switch (type) {
                case 0:
                    sb.append(LOWERANDNUM.charAt(random.nextInt(LOWERANDNUM.length())));
                    break;
                case 1:
                    sb.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
                    break;
                case 2:
                    sb.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
                    break;
            }
        }
        return sb.toString();
    }

    public static String getMd5(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(str.getBytes());
            StringBuffer hexString = new StringBuffer();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02x", b & 0xff));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
